package com.smart.utils;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.smart.common.exception.SmartException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author Administrator
 */
public class FileUtils {


    public static String getFileName(String topFolder, String ext, String fileNamePrefix) {
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String timestamp = String.valueOf(System.currentTimeMillis());
        String s = DigestUtil.md5Hex16(RandomUtil.randomString(12).concat(timestamp));
        String fileName = StrUtil.isNotBlank(fileNamePrefix) ? fileNamePrefix.concat("_").concat(s) : s;
        if (StrUtil.isNotBlank(topFolder)) {
            return topFolder.concat("/").concat(date).concat("/").concat(fileName).concat(ext);
        }
        return "other/".concat(date).concat("/").concat(fileName).concat(ext);
    }

    /**
     * 把文件转化为base64
     */
    public static String encryptToBase64(InputStream inputStream) {
        try {
            byte[] bytes = IOUtils.toByteArray(inputStream);
            return Base64.encodeBase64String(bytes);


        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 把base64转化为byte[]
     */
    public static byte[] base64StringToByte(String base64Str) {
        String substring = base64Str.substring(base64Str.lastIndexOf(",") + 1);
        return Base64.decodeBase64(substring);
    }

    /**
     * byte[]转base64
     */
    public static String byteToBase64String(byte[] b) {
        return Base64.encodeBase64String(b);
    }


    /**
     * 读取上传文件内的文本内容
     */
    public static String multipartFileRead(MultipartFile multipartFile) {

        try {
            StringBuilder stringBuffer = new StringBuilder();
            InputStream inputStream = multipartFile.getInputStream();
            InputStreamReader isReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            BufferedReader bufferedReader = new BufferedReader(isReader);
            while (bufferedReader.ready()) {
                stringBuffer.append(bufferedReader.readLine());
            }
            bufferedReader.close();
            String s = stringBuffer.toString();

            if (StrUtil.isBlank(s)) {
                throw new SmartException("上传文件数据内容为空");
            }
            return s;

        } catch (IOException e) {
            throw new SmartException("上传文件解析失败");

        }

    }


    /**
     * 验证上传的文件是否是图片
     *
     * @param file 文件
     * @return boolean
     */
    public static boolean isImage(MultipartFile file) {
        String filename = file.getOriginalFilename();
        String ext = filename.substring(filename.indexOf("."));
        List<String> extList = List.of(".jpeg", ".jpg", ".gif", ".png", ".bmp");
        return extList.contains(ext);
    }


    /**
     * 判断文件大小处于限制内
     *
     * @param fileSize  文件长度
     * @param limitSize 限制大小
     * @param fileUnit  限制的单位（B,K,M,G）
     * @return
     */
    public static boolean checkFileSize(Long fileSize, int limitSize, String fileUnit) {
        double fileSizeCom = 0;
        if ("B".equalsIgnoreCase(fileUnit)) {
            fileSizeCom = (double) fileSize;
        } else if ("K".equalsIgnoreCase(fileUnit)) {
            fileSizeCom = (double) fileSize / 1024;
        } else if ("M".equalsIgnoreCase(fileUnit)) {
            fileSizeCom = (double) fileSize / (1024 * 1024);
        } else if ("G".equalsIgnoreCase(fileUnit)) {
            fileSizeCom = (double) fileSize / (1024 * 1024 * 1024);
        }
        return !(fileSizeCom > limitSize);
    }


}
